package ling.learn.antlr.common;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.commons.io.FileUtils;

public class AstDumper implements ParseTreeListener {

  private StringBuilder stream;

  private int level;

  private boolean printPos;

  private boolean startError;

  private Vocabulary vocabulary;

  public void dump(String filePath, ParseTree tree, Vocabulary voc, boolean isPrintPos)
      throws IOException {
    stream = new StringBuilder();
    level = 0;
    vocabulary = voc;
    printPos = isPrintPos;
    startError = false;
    ParseTreeWalker.DEFAULT.walk(this, tree);
    FileUtils.write(new File(filePath), stream.toString(), Charset.forName("MS932"));
  }

  private String getNodeName(TerminalNode node) {
    return vocabulary.getSymbolicName(node.getSymbol().getType());
  }

  private String getNodePos(TerminalNode node) {
    return String.format("(%d,%d)", node.getSymbol().getLine(),
        node.getSymbol().getCharPositionInLine() + 1);
  }

  /**
   * {@inheritDoc}
   *
   * <p>
   * The default implementation does nothing.
   * </p>
   */
  @Override
  public void enterEveryRule(ParserRuleContext ctx) {
    // 階層を作成する
    for (int n = 0; n < level; n++) {
      stream.append("\t");
    }
    int length = ctx.getClass().getSimpleName().length();
    stream.append(ctx.getClass().getSimpleName().substring(0, length - 7));
    stream.append("\r\n");
    level++;
    startError = false;
  }

  /**
   * {@inheritDoc}
   *
   * <p>
   * The default implementation does nothing.
   * </p>
   */
  @Override
  public void exitEveryRule(ParserRuleContext ctx) {
    level--;
  }

  /**
   * {@inheritDoc}
   *
   * <p>
   * The default implementation does nothing.
   * </p>
   */
  @Override
  public void visitTerminal(TerminalNode node) {
    // 階層を作成する
    for (int n = 0; n < level; n++) {
      stream.append("\t");
    }
    stream.append(getNodeName(node));
    if (printPos) {
      stream.append(" ").append(getNodePos(node));
    }
    stream.append(" @").append(node.getText());
    stream.append("\r\n");
    // stream.insert(stream.length() - 2, " @" + node.getText());
  }

  /**
   * {@inheritDoc}
   *
   * <p>
   * The default implementation does nothing.
   * </p>
   */
  @Override
  public void visitErrorNode(ErrorNode node) {
    // 階層を作成する
    for (int n = 0; n < level; n++) {
      stream.append("\t");
    }
    stream.append("Error>> ").append(getNodeName(node));
    if (printPos || !startError) {
      stream.append(getNodePos(node));
    }
    stream.append(" @").append(node.getText());
    stream.append("\r\n");
    startError = true;
    // stream.insert(stream.length() - 2, " #" + node.getText());
  }
}
